package com.xlh.Utils;

import android.util.Log;
import android.view.ViewDebug;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by fang on 2017-12-19.
 */

public class GsonManager {


    public static GsonManager gsmgr=null;

    public Gson gsobj = new Gson();

    public static GsonManager getIns(){
        if(GsonManager.gsmgr == null){
            GsonManager.gsmgr = new GsonManager();
        }
        return GsonManager.gsmgr;
    }

    public <T> T jsonToAnyObject(String s, Class<T> clz) {
        T t=null;
        try{
            t =  gsobj.fromJson(s,clz);
        }catch (JsonParseException e){

            String info="";
            for(StackTraceElement es : e.getStackTrace()){
                info+=String.format("FileName %s ",es.getFileName());
                info+=String.format("Class %s ",es.getClassName());
                info+=String.format("MethodName %s ",es.getMethodName());
                info+=String.format("LineNumber %s ",es.getLineNumber());
            }
            info+= String.format("ocalizedMessage %s\n",e.getLocalizedMessage());
            Log.e("【GSON】ToAnyObject error",info);
        }
        return t;


    }

    public <T> String objectToJsonStr(T e) throws RuntimeException{

        return gsobj.toJson(e);

    }

    public HashMap<String, String>  jsonStringToMap(String s) {

        HashMap<String, String> map = new HashMap<String,String>();
        try{
            Type type = new TypeToken<HashMap<String, String>>(){}.getType();
            //Map<String, String> map2 = gsobj.fromJson(s, type);
            map =  gsobj.fromJson(s, type);
        }catch (JsonParseException e){

            String info="";
            for(StackTraceElement es : e.getStackTrace()){
                info+=String.format("FileName %s ",es.getFileName());
                info+=String.format("Class %s ",es.getClassName());
                info+=String.format("MethodName %s ",es.getMethodName());
                info+=String.format("LineNumber %s ",es.getLineNumber());
            }
            info+= String.format("ocalizedMessage %s\n",e.getLocalizedMessage());
            Log.e("【GSON】JssToMap error",info);
        }
        return map;

    }




}
